package com.nstskj.study.netty.tcp.netty.protocol.definition.strategy.impl;

import cn.hutool.core.collection.CollUtil;
import com.nstskj.study.netty.tcp.netty.protocol.definition.ProtocolMsgBeanDefinition;
import com.nstskj.study.netty.tcp.netty.protocol.definition.scan.ProtocolInputMsgScan;
import com.nstskj.study.netty.tcp.netty.protocol.definition.strategy.ProtocolMsgBeanDefinitionStrategy;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ZhouChuGang
 * @version 1.0
 * @project nstskj-study-netty-tcp-spring
 * @date 2021/4/20 21:34
 * @Description
 */
@Slf4j
@Component
public class SpringProtocolMsgBeanDefinitionStrategy implements ProtocolMsgBeanDefinitionStrategy, SmartInitializingSingleton {

    private final Map<Short, ProtocolMsgBeanDefinition> msgBeanDefinitionMap = new ConcurrentHashMap<>();

    @Override
    public ProtocolMsgBeanDefinition getProtocolMsgBeanDefinition(short cmd) {
        return msgBeanDefinitionMap.get(cmd);
    }

    /**
     * 在所有Bean创建完成后调用
     */
    @Override
    public void afterSingletonsInstantiated() {
        //这里扫描指定的包路径，并把 msg 输入的bean转换为 beandefinition
        ProtocolInputMsgScan protocolInputMsgScan = new ProtocolInputMsgScan("com.nstskj.study.netty.tcp.netty.protocol.message.in");
        Map<Short, ProtocolMsgBeanDefinition> msgBeanDefinitionMap = null;
        try {
            msgBeanDefinitionMap = protocolInputMsgScan.getMsgBeanDefinitionMap();
            if (CollUtil.isNotEmpty(msgBeanDefinitionMap)) {
                this.msgBeanDefinitionMap.putAll(msgBeanDefinitionMap);
            }
        } catch (Exception e) {
            log.error("扫描bean失败 ", e);
        }
    }
}
